<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拍卖DApp - Chrome适配版</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <style>
        /* 谷歌字体兼容 */
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
            background-color: #f8f9fa;
        }
        .container {max-width: 1200px; margin-top: 4rem;}
        .nav-link.active {color: #007bff !important;}
        .card {box-shadow: 0 2px 4px rgba(0,0,0,0.05); border-radius: 10px;}
        .function-btn {margin: 0.5rem; border-radius: 6px;}
        .alert {display: none; animation: fadeOut 3s ease;}
        @keyframes fadeOut {from {opacity: 1;} to {opacity: 0;}}
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow sticky-top">
        <div class="container">
            <a class="navbar-brand" href="#"><img src="https://via.placeholder.com/30x30" alt="Logo"> 拍卖DApp</a>
            <div class="navbar-nav">
                <a class="nav-link active" href="#home">首页</a>
                <a class="nav-link" href="#functions">功能</a>
            </div>
        </div>
    </nav>

    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card p-4 mb-4">
                    <h2 class="text-center mb-4">当前拍卖状态</h2>
                    <div id="status" class="text-muted">
                        <div class="d-flex justify-content-between mb-3">
                            <span>最高出价者：</span>
                            <span id="highestBidder">-</span>
                        </div>
                        <div class="d-flex justify-content-between mb-3">
                            <span>最高出价：</span>
                            <span id="highestBid">- ETH</span>
                        </div>
                        <div class="d-flex justify-content-between mb-3">
                            <span>结束时间：</span>
                            <span id="bidEndTime">-</span>
                        </div>
                        <div class="d-flex justify-content-between">
                            <span>状态：</span>
                            <span id="auctionStatus" class="fw-bold"></span>
                        </div>
                    </div>
                </div>

                <div class="card p-4">
                    <h3 class="mb-3">操作面板</h3>
                    <div class="alert alert-success" id="successAlert">操作成功！</div>
                    <div class="alert alert-danger" id="errorAlert">操作失败，请检查钱包</div>

                    <div id="bidSection" class="mb-4">
                        <h5>提交出价</h5>
                        <form id="bidForm" class="input-group">
                            <input type="number" step="0.01" class="form-control" id="bidAmount" placeholder="输入出价（≥0.01 ETH）" required>
                            <button type="submit" class="btn btn-success ms-2">提交出价</button>
                        </form>
                    </div>

                    <button id="withdrawBtn" class="btn btn-warning me-2">撤回未中标出价</button>
                    <button id="endAuctionBtn" class="btn btn-danger">结束拍卖（仅所有者可见）</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 谷歌浏览器优化脚本 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/web3/1.7.0/web3.min.js"></script>
    <script>
        // === 配置项 === //
        const CONTRACT_ADDR = "0xYourContractAddress"; // 替换为合约地址
        const CONTRACT_ABI = [
            // 在此粘贴合约ABI数组
        ];

        let web3, contract, currentAccount, ownerAddr;

        // === 初始化 === //
        async function init() {
            if (!window.ethereum) {
                alert("请在Chrome中安装MetaMask钱包");
                return;
            }

            web3 = new Web3(window.ethereum);
            await window.ethereum.request({ method: 'eth_requestAccounts' });
            currentAccount = (await web3.eth.getAccounts())[0];
            
            contract = new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDR);
            ownerAddr = await contract.methods.owner().call();
            
            setInterval(fetchStatus, 1500);
            fetchStatus();
        }

        // === 获取状态 === //
        async function fetchStatus() {
            try {
                const [hb, hbAddr, endTime, isEnded] = await Promise.all([
                    contract.methods.highestBid().call(),
                    contract.methods.highestBidder().call(),
                    contract.methods.bidEndTime().call(),
                    contract.methods.ended().call()
                ]);

                document.getElementById('highestBid').textContent = web3.utils.fromWei(hb, 'ether');
                document.getElementById('highestBidder').textContent = hbAddr || "-";
                document.getElementById('bidEndTime').textContent = new Date(endTime * 1000).toLocaleString();
                document.getElementById('auctionStatus').textContent = isEnded ? "已结束" : "进行中";
                
                // 控制按钮可见性
                document.getElementById('endAuctionBtn').style.display = currentAccount === ownerAddr && !isEnded ? "block" : "none";
            } catch (err) {
                console.error("状态获取失败:", err);
            }
        }

        // === 出价处理 === //
        document.getElementById('bidForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const eth = parseFloat(document.getElementById('bidAmount').value);
            if (isNaN(eth) || eth < 0.01) return alert("请输入有效金额");

            try {
                await contract.methods.bid().send({
                    from: currentAccount,
                    value: web3.utils.toWei(eth, 'ether')
                });
                showAlert('successAlert');
                document.getElementById('bidForm').reset();
            } catch (err) {
                showAlert('errorAlert', err.message.split(': ')[1] || "出价失败");
            }
        });

        // === 撤回处理 === //
        document.getElementById('withdrawBtn').addEventListener('click', async () => {
            try {
                await contract.methods.withdraw().send({ from: currentAccount });
                showAlert('successAlert');
            } catch (err) {
                showAlert('errorAlert', "撤回失败：" + err.message);
            }
        });

        // === 结束拍卖 === //
        document.getElementById('endAuctionBtn').addEventListener('click', async () => {
            if (currentAccount !== ownerAddr) return showAlert('errorAlert', "只有所有者可操作");
            
            try {
                await contract.methods.auctionEnd().send({ from: currentAccount });
                showAlert('successAlert');
            } catch (err) {
                showAlert('errorAlert', "结束失败：" + err.message);
            }
        });

        // === 提示框 === //
        function showAlert(alertId, msg = '') {
            const el = document.getElementById(alertId);
            el.textContent = msg || el.textContent;
            el.style.display = 'block';
            setTimeout(() => el.style.display = 'none', 3000);
        }

        // 页面加载后初始化
        window.onload = init();
    </script>
</body>
</html>